package com.cswnode.Util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author csw
 * @create 2020/9/21 14:36
 */
//敏感词工具类
@Component
public class SensitiveUtil {
    private static final Logger logger = LoggerFactory.getLogger(SensitiveUtil.class);
    //替换符
    private static final String REPLACEMENT = "***";
    //根节点
    private TrieNode rootNode = new TrieNode();
    //注解表示此方位为初始化方法
    //SensitiveUtil被实例化的时候，该方法自动被调用
    @PostConstruct
    public void init(){
        try(
                //加载文件
                InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("Sensitive-Words.txt");
                BufferedReader Reader = new BufferedReader(new InputStreamReader(resourceAsStream));
        ){
                String keyword;
                while ((keyword = Reader.readLine()) != null){
                    //添加前缀树
                    this.addKeyword(keyword);
                }
        }catch (IOException e){
            logger.error("读取敏感词文件失败"+e.getMessage());
        }

    }

    /**
     * 过滤敏感词
     * @param text 带过滤敏感词
     * @return  处理后的敏感词
     */
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        //指针1
        TrieNode tempNode = rootNode;
        //指针2
        int begin = 0;
        //指针3
        int position = 0;
        //结果
        StringBuilder sb = new StringBuilder();

        while (position < text.length()) {
            char c = text.charAt(position);
            //跳过符号
            if (isSymbol(c)){
                //若指针1处于根节点,将此符号留着，让指针2向下走
                if (tempNode == rootNode){
                    sb.append(c);
                    begin++;
                }
                //无论符号在开头或中间，指针三都向下走一步
                position++;
                continue;
            }

            //检查下级节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null){
                //以begin开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                //进入下一个位置
                position = ++begin;
                //重新指向根节点
                tempNode = rootNode;
            }else if (tempNode.getKeywordEnd()){
                sb.append(REPLACEMENT);
                //进入下一个位置
                begin = ++position;
                //重新指向根节点
                tempNode = rootNode;
            }else {
                //检查下一个字符
                position++;
            }
        }

        //将最后的字符串计入结果
        sb.append(text.substring(begin));
        return sb.toString();
    }

    //判断是否为符号
    private Boolean isSymbol(Character c){
        //0x2E80~0x9FFF为东亚字符不是特殊符号
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    /**
     * 将敏感词加入到前缀树
     * @param keyword
     */
    private void addKeyword(String keyword){
        //临时节点
        TrieNode tempNode = rootNode;
        for (int i = 0 ;i < keyword.length();i++){
            char c = keyword.charAt(i);
            //获得子节点
            TrieNode subNode = tempNode.getSubNode(c);
            //如果没有获得C值的子节点，就新建一个头节点
            if (subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c,subNode);
            }
            //指向子节点，进入下一轮循环
            tempNode = subNode;
            //设置结束的标符
            if (i == keyword.length() - 1){
                tempNode.setKeywordEnd(true);
            }
        }
    }

    //前缀树节点
    private class TrieNode{
        /**
         * 定义结束标识符
         * 判断是否为单词结尾
         */
        private Boolean isKeywordEnd = false;

        /**
         * 子节点(key是下级字符，value是下级节点)
         */
        private Map<Character,TrieNode> subNodes = new HashMap<>();

        public Boolean getKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(Boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        /**
         * 添加子节点
         * @param c
         * @param t
         */
        public void addSubNode(Character c,TrieNode t){
            subNodes.put(c,t);
        }
        /**
         * 获得子节点
         */
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }

    }

}
